import * as BL from '../index';


/**
 * 资源预加载信息接口
 * @param key 资源对象的键名
 * @param rootUrl 不带扩展的文件名称
 * @param name 文件所在根目录地址
 * @param url 完整地址
 * @param blobUrl 缓存数据地址
 * @param extension 文件扩展
 * @param blob 缓存数据（预留）
 */
interface IBufferLoadInfo {
    key: string,
    rootUrl: string,
    name: string,
    url: string,
    blobUrl: string,
    extension: string,
    blob?: Blob,
}

/**
 * 资源预加载（加载至缓存）组件
 */
class BufferLoad {
    /**
     * 资源预加载信息集合
     */
    public readonly infos: Array<IBufferLoadInfo> = [];

    /**
     * 根据完整地址获取预加载信息
     * @param url 完整地址
     * @returns 预加载信息
     */
    public getInfo(rawUrl: string): IBufferLoadInfo | null {
        for (const info of this.infos) {
            if (rawUrl === info.url) return info;
        }
        return null;
    }

    /**
     * 预加载资源
     * @param urls 资源对象
     * @returns 资源预加载信息集合
     */
    public async load(urls: BL.ILoose<string>): Promise<IBufferLoadInfo[]> {
        this.generateInfo(urls);
        for (const info of this.infos) {
            const arrayBuffer = await BL.Tools.LoadFileAsync(info.url);
            const blob = new Blob([arrayBuffer]);
            info.blob = blob;
            info.blobUrl = URL.createObjectURL(blob);
        }
        return this.infos;
    }

    /**
     * 生成预加载信息（没有缓存数据地址的）
     * @param urls 资源对象
     */
    private generateInfo(urls: BL.ILoose<string>): void {
        for (const key in urls) {
            const url = urls[key];
            const ss = url.split('/');
            const rootUrl = (() => {
                const tmp: Array<string> = [];
                for (let i = 0; i < ss.length - 1; i++) {
                    tmp.push(ss[i]);
                }
                return tmp.join('/') + '/';
            })();
            const ne = ss[ss.length - 1].split('.');
            const name = (() => {
                const tmp: Array<string> = [];
                for (let i = 0; i < ne.length - 1; i++) {
                    tmp.push(ne[i]);
                }
                return tmp.join('.');
            })();
            const extension = '.' + ne[ne.length - 1];

            this.infos.push({
                key: key,
                url: url,
                rootUrl: rootUrl,
                name: name,
                extension: extension,
                blobUrl: '',
            });
        }
    }
}

export { BufferLoad };
export type { IBufferLoadInfo };